<!--
 * Copyright © 2022
 * @Author: zhangxiang
 * @Date: 2022-11-21 17:13:52
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-08-14 18:02:55
 * @Description:
 *
-->

<template>
  <div class="menu-container">
    <el-row type="flex" align="middle">
      <div>系统名称</div>
      <el-input
        v-model="appName"
        style="width: 180px; margin-left: 10px; margin-right: 78px"
        size="small"
        :disabled="!appEditing"
        placeholder="请输入系统名称"
      />
      <el-button
        v-if="!appEditing"
        type="text"
        size="mini"
        @click="appEditing = true"
      >
        修改
      </el-button>
      <el-button
        v-if="appEditing"
        type="text"
        size="mini"
        @click="appCancelClick"
      >
        取消
      </el-button>
      <el-button
        v-if="appEditing"
        type="text"
        size="mini"
        :loading="appConfirming"
        @click="appConfirmClick()"
      >
        确定
      </el-button>
    </el-row>
    <el-divider />
    <el-row style="margin-top: 20px">
      <el-tree
        :data="menuTree"
        node-key="val"
        default-expand-all
        :expand-on-click-node="false"
      >
        <div slot-scope="{ node, data }" class="custom-tree-node">
          <div class="label">
            <div v-if="!data.editing">{{ node.label }}</div>
            <el-input
              v-else
              v-model="data.label"
              style="width: 120px"
              size="mini"
              placeholder="请输入"
            />
          </div>
          <el-button
            v-if="!data.editing"
            type="text"
            size="mini"
            @click="editClick(data)"
          >
            修改
          </el-button>
          <el-button
            v-if="data.editing"
            type="text"
            size="mini"
            @click="cancelClick(data)"
          >
            取消
          </el-button>
          <el-button
            v-if="data.editing"
            type="text"
            size="mini"
            :loading="data.confirming"
            @click="confirmClick(data)"
          >
            确定
          </el-button>
        </div>
      </el-tree>
    </el-row>
  </div>
</template>

<script>
import { updateMenuName } from '@/api/system-mgmt'
import { mapGetters } from 'vuex'
import getPageTitle from '@/utils/get-page-title'

export default {
  name: 'SystemMgmtMenu',
  components: {},
  data() {
    return {
      appName: '',
      appEditing: false,
      appConfirming: false,
      menuTree: [],
      onlyOneChild: null
    }
  },
  computed: {
    ...mapGetters(['menuName', 'permission_routers'])
  },
  watch: {
    menuName: {
      handler(newValue) {
        if (newValue) {
          this.initTreeByRoutes()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {},
  methods: {
    /**
     * @description: 成功处理
     * @return {*}
     */
    async successHandle() {
      this.$message.success({
        message: '修改成功',
        duration: '2000'
      })
      try {
        await this.$store.dispatch('app/syncMenuNames')
        document.title = getPageTitle(
          this.$route.meta.title,
          this.$route.meta.menuNameKey
        )
      } catch (err) {
        console.log(err)
      }
    },
    /**
     * @description: 取消
     * @return {*}
     */
    appCancelClick() {
      this.appEditing = false
      this.appName = this.findNewestMenuName('App', '算网一体编排调度平台')
    },
    /**
     * @description: 确定
     * @return {*}
     */
    appConfirmClick() {
      this.appConfirming = true
      updateMenuName({
        menuKey: 'App',
        menuValue: this.appName
      })
        .then((res) => {
          this.appEditing = false
          this.successHandle()
        })
        .finally(() => {
          this.appConfirming = false
        })
    },
    /**
     * @description: 确定
     * @param {*} data
     * @return {*}
     */
    confirmClick(data) {
      data.confirming = true
      updateMenuName({
        menuKey: data.val,
        menuValue: data.label
      })
        .then((res) => {
          data.editing = false
          this.successHandle()
        })
        .finally(() => {
          data.confirming = false
        })
    },
    /**
     * @description: 取消
     * @param {*} data
     * @return {*}
     */
    cancelClick(data) {
      data.editing = false
      data.label = this.findNewestMenuName(data.val, data.label)
    },
    /**
     * @description: 编辑
     * @param {*} data
     * @return {*}
     */
    editClick(data) {
      data.editing = true
    },
    /**
     * @description: 查找最新菜单名
     * @param {*} key
     * @param {*} value
     * @return {*}
     */
    findNewestMenuName(key, value) {
      if (Object.prototype.hasOwnProperty.call(this.menuName, key)) {
        return this.menuName[key].menuValue
      }
      return value
    },
    /**
     * @description: 是否只有一个菜单
     * @param {*} children
     * @param {*} parent
     * @return {*}
     */
    hasOneShowingChild(children = [], parent) {
      const showingChildren = children.filter((item) => {
        if (item.hidden) {
          return false
        } else {
          // Temp set(will be used if only has one showing child)
          this.onlyOneChild = item
          return true
        }
      })

      // When there is only one child router, the child router is displayed by default
      if (showingChildren.length === 1) {
        return true
      }

      // Show parent if there are no child router to display
      if (showingChildren.length === 0) {
        this.onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return true
      }

      return false
    },
    /**
     * @description: 遍历过滤路由
     * @param {*} tree
     * @param {*} routes
     * @return {*}
     */
    filterRoutes(tree, routes) {
      for (const item of routes) {
        if (!item.hidden) {
          if (
            this.hasOneShowingChild(item.children, item) &&
            (!this.onlyOneChild.children ||
              this.onlyOneChild.noShowingChildren) &&
            !item.alwaysShow
          ) {
            if (this.onlyOneChild.meta) {
              tree.push({
                confirming: false,
                editing: false,
                val: this.onlyOneChild.meta.menuNameKey,
                label: this.findNewestMenuName(
                  this.onlyOneChild.meta.menuNameKey,
                  this.onlyOneChild.meta.title
                )
              })
            }
          } else {
            if (item.meta) {
              tree.push({
                confirming: false,
                editing: false,
                val: item.meta.menuNameKey,
                label: this.findNewestMenuName(
                  item.meta.menuNameKey,
                  item.meta.title
                ),
                children: []
              })
              this.filterRoutes(tree[tree.length - 1].children, item.children)
            }
          }
        }
      }
    },
    /**
     * @description: 初始化tree
     * @return {*}
     */
    initTreeByRoutes() {
      const tree = []
      this.filterRoutes(tree, this.permission_routers)
      this.menuTree = tree
      this.appName = this.findNewestMenuName('App', '算网一体编排调度平台')
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/css/common.less";
.menu-container {
  box-sizing: border-box;
  background: #ffffff;
  box-shadow: 0px 0px 5px 0px rgba(217, 213, 234, 0.5);
  border-radius: 8px;
  margin: 20px;
  min-height: calc(100vh - 90px);
  padding: 20px 30px;

  .custom-tree-node {
    display: flex;
    flex-direction: row;
    align-items: center;
    .label {
      width: 300px;
      .textStyle(15px , 400, #696969);

      /deep/ .el-input__inner {
        height: 24px;
        line-height: 24px;
      }
    }
  }
}
</style>
